﻿using Common;
using IService;
using Microsoft.AspNetCore.Http;
using Model.Models;
using ModelDto;
using SqlserverManager;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;

namespace Service
{
    /// <summary>
    /// 日志服务接口
    /// </summary>
    [Service]
    public class LogService : ILogService
    {

        private readonly IDbConnectionFactory _dbConnectionFactory;
        private readonly IHttpContextAccessor _httpContextAccessor;

        public LogService(IDbConnectionFactory dbConnectionFactory, IHttpContextAccessor httpContextAccessor)
        {
            _dbConnectionFactory = dbConnectionFactory;
            _httpContextAccessor = httpContextAccessor;
        }


        /// <summary>
        /// 登录日志
        /// </summary>
        /// <param name="account">用户信息</param>
        /// <param name="AccountNo">登录账号</param>
        /// <param name="Pwd">登录密码</param>
        /// <param name="LoginState">登录状态</param>
        /// <param name="LoginAction">登录方式</param>
        public void WriteLoginLog(Account account, string AccountNo, string Pwd, string LoginState, string LoginAction)
        {
            try
            {
                var Context = _dbConnectionFactory.CreateDbContext();
                string ipAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress?.ToString();
                var entity = new LoginLog();

                entity.Id = Guid.NewGuid().ToString();
                entity.CreateTime = DateTime.Now;
                entity.CreateUser = account?.Id ?? "";

                entity.CreateUserName = account?.Name ?? "";
                entity.CreateUserCode = account?.AccountNo ?? "";

                entity.Name = account?.Name ?? "";
                entity.AccountNo = AccountNo;
                entity.Pwd = Pwd;
                entity.LoginState = LoginState;
                entity.LoginIP = ipAddress == "::1" ? "127.0.0.1" : _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
                entity.LoginAction = LoginAction;

                Context.Insertable<LoginLog>(entity).ExecuteCommand();

            }
            catch (Exception)
            {

            }
        }

        public void WriteErrorLog(Account account, string RequestPath, string Message, string StackTrace)
        {
            try
            {
                var Context = _dbConnectionFactory.CreateDbContext();
                string ipAddress = _httpContextAccessor.HttpContext.Connection.RemoteIpAddress?.ToString();
                var entity = new ErrorLog();

                entity.Id = Guid.NewGuid().ToString();
                entity.CreateTime = DateTime.Now;
                entity.CreateUser = account?.Id ?? "";

                entity.CreateUserName = account?.Name ?? "";
                entity.CreateUserCode = account?.AccountNo ?? "";

                entity.Message = Message;
                entity.StackTrace = StackTrace;
                entity.RequestPath = RequestPath;
                entity.Ip = ipAddress == "::1" ? "127.0.0.1" : _httpContextAccessor.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

                Context.Insertable<ErrorLog>(entity).ExecuteCommand();

            }
            catch (Exception)
            {

            }
        }

        public void WriteApiLog(Account account, string PushUrl, string PushContent, string ResponseContent, string RequestTime, string State)
        {
            try
            {
                var Context = _dbConnectionFactory.CreateDbContext();

                var entity = new ApiLog();

                entity.Id = Guid.NewGuid().ToString();
                entity.CreateTime = DateTime.Now;
                entity.CreateUser = account?.Id ?? "";

                entity.CreateUserName = account?.Name ?? "";
                entity.CreateUserCode = account?.AccountNo ?? "";

                entity.PushUrl = PushUrl;
                entity.PushContent = PushContent;
                entity.ResponseContent = ResponseContent;
                entity.RequestTime = RequestTime;
                entity.State = State;

                Context.Insertable<ApiLog>(entity).ExecuteCommand();

            }
            catch (Exception)
            {

            }
        }


        public async Task<(List<LoginLog>,int)>  GetLoginLogList(LogRequest request)
        {
            var Context = _dbConnectionFactory.CreateDbContext();

            var query = Context.Queryable<LoginLog>();

            if (!string.IsNullOrWhiteSpace(request.StarTime))
            {
                var dt = CommonFun.ConvertTime(request.StarTime);
                if (dt != null)
                {
                    query = query.Where(a => a.CreateTime >= dt.Value);
                }

            }
            if (!string.IsNullOrWhiteSpace(request.EndTime))
            {
                var dt = CommonFun.ConvertTime(request.EndTime);
                if (dt != null)
                {
                    query = query.Where(a => a.CreateTime <= dt.Value);
                }

            }


            if (!string.IsNullOrWhiteSpace(request.KeyWords))
            {
                if (request.KeyWords == "登录失败")
                {
                    query = query.Where(a => a.LoginState == "登录失败");
                }
                else if (request.KeyWords == "登录成功")
                {
                    query = query.Where(a => a.LoginState == "登录成功");
                }
                else
                {
                    query = query.Where(a => a.CreateUserName.Contains(request.KeyWords) || a.CreateUserCode.Contains(request.KeyWords));
                }


            }
            if (request.PageIndex <= 0)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize <= 0)
            {
                request.PageSize = 10;
            }


            RefAsync<int> count = 0;

            var list = await query.OrderByDescending(a => a.CreateTime).ToPageListAsync(request.PageIndex, request.PageSize, count);


            return new(list, count);

        }

        public async Task<(List<ErrorLog>, int)> GetErrorLogList(LogRequest request)
        {
            var Context = _dbConnectionFactory.CreateDbContext();

            var query = Context.Queryable<ErrorLog>();

            if (!string.IsNullOrWhiteSpace(request.StarTime))
            {
                var dt = CommonFun.ConvertTime(request.StarTime);
                if (dt != null)
                {
                    query = query.Where(a => a.CreateTime >= dt.Value);
                }

            }
            if (!string.IsNullOrWhiteSpace(request.EndTime))
            {
                var dt = CommonFun.ConvertTime(request.EndTime);
                if (dt != null)
                {
                    query = query.Where(a => a.CreateTime <= dt.Value);
                }

            }
            if (!string.IsNullOrWhiteSpace(request.KeyWords))
            {
                query = query.Where(a => a.CreateUserName.Contains(request.KeyWords) || a.CreateUserCode.Contains(request.KeyWords));

            }


            if (request.PageIndex <= 0)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize <= 0)
            {
                request.PageSize = 10;
            }

            RefAsync<int> count = 0;

            var list = await query.OrderByDescending(a => a.CreateTime).ToPageListAsync(request.PageIndex, request.PageSize, count);


            return new(list, count);
        }

        public async Task<(List<ApiLog>, int)> GetApiLogList(LogRequest request)
        {
            var Context = _dbConnectionFactory.CreateDbContext();

            var query = Context.Queryable<ApiLog>();

            if (!string.IsNullOrWhiteSpace(request.StarTime))
            {
                var dt = CommonFun.ConvertTime(request.StarTime);
                if (dt != null)
                {
                    query = query.Where(a => a.CreateTime >= dt.Value);
                }

            }
            if (!string.IsNullOrWhiteSpace(request.EndTime))
            {
                var dt = CommonFun.ConvertTime(request.EndTime);
                if (dt != null)
                {
                    query = query.Where(a => a.CreateTime <= dt.Value);
                }

            }
            if (!string.IsNullOrWhiteSpace(request.KeyWords))
            {
                query = query.Where(a => a.CreateUserName.Contains(request.KeyWords) || a.CreateUserCode.Contains(request.KeyWords));

            }


            if (request.PageIndex <= 0)
            {
                request.PageIndex = 1;
            }
            if (request.PageSize <= 0)
            {
                request.PageSize = 10;
            }

            RefAsync<int> count = 0;

            var list = await query.OrderByDescending(a => a.CreateTime).ToPageListAsync(request.PageIndex, request.PageSize, count);


            return new(list, count);

        }


    }
}
